﻿using Comm520;
using RFIDSystem.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RFIDSystem
{
    
    

    public partial class SalePos : BaseForm
    {
        DLC520Socket dlcsocket;

        List<sale_order> orders;

        public SalePos()
        {
            InitializeComponent();
            dlcsocket = this.GetSocket(SocketPort);
            dlcsocket.DataReceived += new DLC520Socket.MachineDataReceived(DataReceived);
        }

        private void SalePos_Load(object sender, EventArgs e)
        {
            orders = new List<sale_order>();
            this.gridProductList.AutoGenerateColumns = false;
            BindCheckStockList();
        }

        private void AddProductInList(string rfid)
        {
            var product = DAL.product_product.FirstOrDefault(p => p.product_rfid == rfid);

            if (product == null)
            {
                //MessageBox.Show("基础产品库中无此RFID的产品，请先维护产品!");
                return;
            }
            sale_order orderItem;
            var query = from o in orders
                        where o.product_product.product_id == product.product_id
                        select o;


            if (query.FirstOrDefault() == null)
            {
                int maxId = 0;
                if (orders != null && orders.Count > 0)
                {
                    maxId = (from o in orders
                             select o.sale_id).Max();
                }
                
                orderItem = new sale_order()
                {

                    sale_id = maxId + 1,
                    product_product = product,
                    sale_product_name = product.product_name,
                    sale_product_model = product.product_model,
                    sale_qty = 1,
                    sale_price = product.product_price,
                    sale_money = product.product_price,
                };

                orders.Add(orderItem);
            }
            else
            {
                orderItem = query.FirstOrDefault();
                orderItem.sale_qty++;
                orderItem.sale_money = orderItem.sale_money + orderItem.sale_price;
            }
        }

        private void BindOrderList()
        {
            var query = from o in orders
                        select o;

            List<sale_order> orderList = query.ToList();

            decimal? moneySum = 0;
            foreach(sale_order o in orderList)
            {
                moneySum = moneySum + o.sale_money;
            }

            lblSumMoney.Text = string.Format("总计：￥{0}", moneySum);

            this.gridProductList.DataSource = orderList;
        }

        private void BindCheckStockList()
        {
            lbList.Items.Clear();
            var query = (
                            from c in DAL.sale_order
                            group c by new { c.sale_code, c.create_datetime } into temp
                            orderby temp.Key.sale_code descending
                            select new { temp.Key.sale_code, temp.Key.create_datetime, count = temp.Count() }

                        ).ToList();

            for (int i = 0; i < query.Count(); i++)
            {
                string temp = string.Format("{0}|{1}", query[i].sale_code, query[i].create_datetime);
                lbList.Items.Add(temp);
            }

        }

        private void txtProductRFID_TextChanged(object sender, EventArgs e)
        {

            if (txtProductRFID.Text == "")
                return;

          
            AddProductInList(txtProductRFID.Text);
            txtProductRFID.Text = "";
            BindOrderList();
        }

        

        private void btnSaveOrder_Click(object sender, EventArgs e)
        {
            if (this.orders == null || this.orders.Count == 0)
            {
                MessageBox.Show("订单为空，无需下单");
                return;
            }

            string orderCode = "O" + DateTime.Now.ToString("yyyyMMddhhmmss");
            DateTime orderTime = DateTime.Now;

            foreach(sale_order o in orders)
            {
                o.sale_code = orderCode;
                o.create_datetime = orderTime;

            }

            DAL.sale_order.AddRange(orders);
            DAL.SaveChanges();

            MessageBox.Show("下单成功，自动打印小票");
            this.orders.Clear();
            BindOrderList();
            BindCheckStockList();

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int currentId = (int)gridProductList.CurrentRow.Cells["sale_id"].Value;
            orders.Remove(orders.Find(o => o.sale_id == currentId));
            txtProductRFID.Text = "";
            BindOrderList();
        }

        bool DataReceived(string data)
        {
            try
            {

                //datetime=20160507163510,ip=192.168.1.10,result=15,event=1,cardx4=54585382,mdno=487,redio=0,photono=32,
                string cardid = "", ip = "", datetime = "", occur = "", result = "", before = "", after = "", mdno = "", cdno = "", dealtype = "", macno = "", serno = "", status = "";
                string[] items = data.Split(',');
                for (int index = 0; index < items.Length; index++)
                {
                    if (items[index].IndexOf("cardid", 0) >= 0 || items[index].IndexOf("cardx4", 0) >= 0)
                    {
                        cardid = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("ip", 0) >= 0)
                    {
                        ip = items[index].Substring(3);
                    }
                    if (items[index].IndexOf("datetime", 0) >= 0)
                    {
                        datetime = items[index].Substring(9);
                    }
                    if (items[index].IndexOf("occur", 0) >= 0)
                    {
                        occur = items[index].Substring(6);
                    }
                    if (items[index].IndexOf("result", 0) >= 0)
                    {
                        result = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("before", 0) >= 0)
                    {
                        before = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("after", 0) >= 0)
                    {
                        after = items[index].Substring(6);
                    }
                    if (items[index].IndexOf("mdno", 0) >= 0)
                    {
                        mdno = items[index].Substring(5);
                    }
                    if (items[index].IndexOf("cdno", 0) >= 0)
                    {
                        cdno = items[index].Substring(5);
                    }
                    if (items[index].IndexOf("dealtype", 0) >= 0)
                    {
                        dealtype = items[index].Substring(9);
                    }
                    if (items[index].IndexOf("status", 0) >= 0)
                    {
                        status = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("macno", 0) >= 0)
                    {
                        macno = items[index].Substring(6);
                    }
                    if (items[index].IndexOf("serno", 0) >= 0)
                    {
                        serno = items[index].Substring(6);
                    }

                }
                //AddProductInList(cardid);
                this.Invoke(new Action<TextBox, string>((t, s) => t.Text = s), new object[] { txtProductRFID, cardid });
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void gridProductList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (gridProductList.Rows.Count > 0 && e.RowIndex >= 0)
            {
                string columnName = gridProductList.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name;
                if (columnName == "ProductQty" || columnName == "ProductAmount")
                {
                    foreach (DataGridViewRow r in this.gridProductList.Rows)
                    {
                        int saleId = (int)r.Cells["sale_id"].Value;

                        var order = orders.Find(o => o.sale_id == saleId);
                        order.sale_qty = (int)r.Cells["ProductQty"].Value;
                        order.sale_price = (decimal)r.Cells["ProductSalePrice"].Value;
                        order.sale_money = columnName == "ProductQty" ? 
                            order.sale_qty * order.sale_price 
                            : (decimal)r.Cells["ProductAmount"].Value;

                    }
                    BindOrderList();
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (lbList.SelectedItem == null)
            {
                MessageBox.Show("先选择一条需要打印的订单记录");
                return;
            }

            var printForm = new SalePosPring();
            printForm.CheckCode = lbList.SelectedItem.ToString().Split('|')[0];
            printForm.CheckTime = lbList.SelectedItem.ToString().Split('|')[1];
            printForm.Show();
        }
    }
}
